package com.wry.controller;

import com.alibaba.fastjson.JSON;
import com.wry.model.ElasticArticle;
import com.wry.model.Order;
import com.wry.repository.ElasticArticleRepository;
import com.wry.utils.PageResponse;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <h1>  <h1>
 *
 * @author wry
 * @since 2023/8/26 9:37
 */
@RestController
@RequestMapping("article")
public class ElasticArticleController {

    @Resource
    private ElasticArticleRepository elasticArticleRepository;
    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 批量创建文档
     *
     * @param articleList 文档集合
     * @return
     */
    @PostMapping("save-batch")
    public String saveBatch(@RequestBody List<ElasticArticle> articleList){
        if (articleList.isEmpty()){
            return "文档不能为空！";
        }
        elasticArticleRepository.saveAll(articleList);
        return "ok";
    }

    /**
     * 分页查询，不带条件
     * @param pageIndex 页码
     * @param pageSize 页大小
     * @return
     */
    @GetMapping("find-all")
    public String findAll(@RequestParam Integer pageIndex, @RequestParam Integer pageSize){
        final Page<ElasticArticle> page = elasticArticleRepository.findAll(PageRequest.of(pageIndex, pageSize));
        PageResponse<ElasticArticle> pageResponse = new PageResponse<>();
        pageResponse.setTotal(page.getTotalElements());
        pageResponse.setResult(page.getContent());
        return JSON.toJSONString(pageResponse);
    }

    /**
     * 根据文章 title 查
     * @param pageIndex 页码
     * @param pageSize 页大小
     * @return
     */
    @GetMapping("find")
    public String findAll(@RequestParam String title,@RequestParam Integer pageIndex, @RequestParam Integer pageSize){
        CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()
                .and(new Criteria("title").contains(title)))
                .setPageable(PageRequest.of(pageIndex, pageSize));
        SearchHits<Order> searchHits = elasticsearchRestTemplate.search(criteriaQuery, Order.class);
        return JSON.toJSONString(PageResponse.page(searchHits));
    }
}
